%clearvars

filePath = matlab.desktop.editor.getActiveFilename;
fprintf('%s\n',filePath);

repository_base = fileparts(fileparts(filePath));
addpath(fullfile(repository_base, "scripts"));
addpath(fullfile(repository_base, "scripts", "libs"));

if ~exist(fullfile(repository_base, "scripts", "libs", "bvaloader"))
   fprintf("bva_loader was not found.\nPlease clone 'https://github.com/stefanSchinkel/bvaloader.git' repository into REPO_BASE\scripts\libs\n") 
   return
end

addpath(fullfile(repository_base, "scripts", "libs", "bvaloader"));


%session_idx = 1;

session_list{1} = 'sub-A';
session_list{2} = 'sub-B';
session_list{3} = 'sub-C';
session_list{4} = 'sub-D';
session_list{5} = 'sub-E';
session_list{6} = 'sub-F';
session_list{7} = 'sub-G';
session_list{8} = 'sub-H';
session_list{9} = 'sub-I';
session_list{10} = 'sub-J';
session_list{11} = 'sub-K';

fs = 1000;

filt_order = 2;
filt_range = [0.1 40];

[b, a] = butter(filt_order, filt_range/(fs/2), 'bandpass');

session = session_list{session_idx};

f_base = fullfile(repository_base, 'eeg');
save_base = fullfile(repository_base, 'epochs');
mkdir(save_base);

condition = [1 4;
             2 5;
             3 6];

tasks = {'low', 'mid', 'high'};

markers = [2 8 32];
range = [-0.1 0.5];
baseline = [-0.05 0];

for m = 1:size(condition, 1)
    for n = 1:length(markers)
        epochs.att{m}.marker{n} = {};
    end
end

for m = 1:size(condition, 1)
    f_idx = condition(m, :);
    for n = 1:length(f_idx)
        f_name = session + "_task-" + tasks{m} + "_run-" + string(f_idx(n)) + "_eeg";
        f_dir = fullfile(f_base, session, "eeg", f_name);
        sig(n) = siSig(f_dir);
        sig(n).filtfilt(b,a);
    end
    sig = siSig(sig);
    for k = 1:length(markers)
        marker = markers(k);
        epochs.att{m}.marker{k} = siEpoch(sig, marker, range, baseline);
    end
end

save(fullfile(save_base, strcat(session, '_filt_', string(filt_order), '_', string(filt_range(1)), '_', string(filt_range(2)),'.mat')), 'epochs')